// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: wsfuyibing <682805@qq.com>
// Date: 2025-04-09

package database

import (
	"context"
	"errors"
	"gitee.com/go-libs/log"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"time"
)

type logging struct {
	cfg *Config
	key string
}

func (o *logging) LogMode(logger.LogLevel) logger.Interface      { return o }
func (o *logging) Info(context.Context, string, ...interface{})  {}
func (o *logging) Warn(context.Context, string, ...interface{})  {}
func (o *logging) Error(context.Context, string, ...interface{}) {}

func (o *logging) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
	text, _ := fc()
	log.Infofc(ctx, `driver="%s", key="%s", duration="%dms", sql="%s"`, o.cfg.Driver, o.key, time.Now().Sub(begin).Milliseconds(), text)

	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		log.Errorfc(ctx, `driver="%s", key="%s", error="%v"`, o.cfg.Driver, o.key, err)
	}
}

func (o *logging) init() *logging { return o }
